package com.zbkj.service.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.novel.NovelAuthoritytEntity;
import com.zbkj.common.model.novel.NovelEntity;
import com.zbkj.common.model.novel.NovelRollChapterEntity;
import com.zbkj.common.request.NovelChapterUpdateRequest;
import com.zbkj.common.response.NovelContentResponse;
import com.zbkj.service.dao.NovelRollChapterDao;
import com.zbkj.service.service.NovelAuthorityService;
import com.zbkj.service.service.NovelRollChapterService;
import com.zbkj.service.service.NovelService;
import com.zbkj.service.service.UserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;


/**
 * 小说章节表 接口实现类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * @author: 大粽子
 * +----------------------------------------------------------------------
 * @date Mon Apr 22 15:31:27 CST 2024
 * +----------------------------------------------------------------------
 * @email stivepeim@outlook.com
 * +----------------------------------------------------------------------
 */

@Service("novelRollChapterService")
public class NovelRollChapterServiceImpl extends ServiceImpl<NovelRollChapterDao, NovelRollChapterEntity> implements NovelRollChapterService {

    @Resource
    private NovelRollChapterDao dao;

    @Autowired
    private NovelService novelService;

    @Autowired
    private UserService userService;

    @Autowired
    private NovelAuthorityService novelAuthorityService;
    @Override
    public List<NovelRollChapterEntity> getChaptersByNovelId(Integer id) {

        return dao.getChaptersByNovelId(id);
    }

    @Override
    public void chapterUpdate(NovelChapterUpdateRequest request) {
        NovelEntity novel = novelService.getById(request.getNovelId());

        if(ObjectUtil.isNull(novel)){
            throw new CrmebException("书不存在");
        }


//        Integer userId = 2;
        Integer userId = userService.getUserId();
        List<NovelAuthoritytEntity> list = novelAuthorityService.getAllByNovelId(request.getNovelId());

        if(list.stream().noneMatch(obj -> Objects.equals(obj.getUid(), userId))){
            throw new CrmebException("用户无编辑权限");
        };
        NovelRollChapterEntity novelRollChapterEntity = dao.selectById(request.getId());

        int newCount = countWords(request.getContent());

        if(ObjectUtil.isNotNull(novelRollChapterEntity)){
            if(novelRollChapterEntity.getIsOpen()==1)
                throw new CrmebException("章节已发布，请先下架");
            int count = countWords(novelRollChapterEntity.getContent());
            BeanUtils.copyProperties(request,novelRollChapterEntity);
            novel.setLength(novel.getLength()-count+newCount);
            dao.updateById(novelRollChapterEntity);
            novelService.updateById(novel);
        }else{
            novelRollChapterEntity = new NovelRollChapterEntity();
            BeanUtils.copyProperties(request,novelRollChapterEntity);
            novelRollChapterEntity.setIsDel(0);
            novelRollChapterEntity.setIsShow(1);
            novelRollChapterEntity.setIsOpen(0);
            novel.setTotalChapter(novel.getTotalChapter()+1);
            novelRollChapterEntity.setChapterNum(novel.getTotalChapter());
            dao.insert(novelRollChapterEntity);
            novelService.updateById(novel);
        }
    }

    public String chapterOpen(Integer id){
        Integer userId = userService.getUserId();
        NovelRollChapterEntity rollChapterEntity = dao.selectById(id);
        if(!Objects.equals(novelService.getById(rollChapterEntity.getNovelId()).getUId(), userId)) {
            throw new CrmebException("不是该书的发布者");
        }
        rollChapterEntity.setIsOpen(1);
        dao.updateById(rollChapterEntity);
        return "发布成功";
    }

    @Override
    public String reduce(Integer id) {
        Integer userId = userService.getUserId();
        NovelRollChapterEntity rollChapterEntity = dao.selectById(id);
        if(!Objects.equals(novelService.getById(rollChapterEntity.getNovelId()).getUId(), userId)) {
            throw new CrmebException("不是该书的发布者");
        }
        rollChapterEntity.setIsDel(0);
        dao.updateById(rollChapterEntity);
        return "回收成功";
    }

    @Override
    public String delete(Integer id) {
        Integer userId = userService.getUserId();
        NovelRollChapterEntity rollChapterEntity = dao.selectById(id);
        if(!Objects.equals(novelService.getById(rollChapterEntity.getNovelId()).getUId(), userId)) {
            throw new CrmebException("不是该书的发布者");
        }
        rollChapterEntity.setIsDel(1);
        dao.updateById(rollChapterEntity);
        return "删除成功";
    }

    @Override
    public String chapterunrelease(Integer id) {
        Integer userId = userService.getUserId();
        NovelRollChapterEntity rollChapterEntity = dao.selectById(id);
        if(!Objects.equals(novelService.getById(rollChapterEntity.getNovelId()).getUId(), userId)) {
            throw new CrmebException("不是该书的发布者");
        }
        rollChapterEntity.setIsOpen(0);
        dao.updateById(rollChapterEntity);
        return "下架成功";
    }

    @Override
    public List<NovelRollChapterEntity> getlastZJById(Integer id) {
        return dao.getlastZJById(id);
    }

    @Override
    public NovelContentResponse getContent(Integer id) {
        NovelRollChapterEntity content = dao.getContent(id);
        NovelContentResponse novelContentResponse = new NovelContentResponse();
        novelContentResponse.setContent(content.getContent());
        novelContentResponse.setCanread(true);
        return novelContentResponse;
    }

    public int countWords(String html) {
        // 移除所有HTML标签
        String text = html.replaceAll("<[^>]+>", " ");

        // 替换多个空格为一个空格（包括制表符和换行符）
        text = text.replaceAll("\\s+", " ");

        // 去掉首尾空格
        text = text.trim();

        // 判断是否为空字符串
        if (text.isEmpty()) {
            return 0;
        }

        // 分割字符串计算单词数
        String[] words = text.split(" ");
        return words.length;
    }

    /**
     * NovelRollChapter列表查询
     * @param request 默认是是体类 根据自己需求修改或者创建自己的request
     * @param pageParamRequest 分页参数对象
     * @return
     */
//    @Override
//    public PageUtils queryPage(NovelRollChapterEntity request, PageParamRequest pageParamRequest) {
//        PageHelper.startPage(pageParamRequest.getPageNum(), pageParamRequest.getPageSize());
//
//        //列表查询 NovelRollChapter 类的多条件查询
//        LambdaQueryWrapper<NovelRollChapter> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        NovelRollChapter model = new NovelRollChapter();
//        BeanUtils.copyProperties(request, model);
//        lambdaQueryWrapper.setEntity(model);
//        return dao.selectList(lambdaQueryWrapper);
//    }

}
